package com.hu.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hu.adapter.UserBuilder;
import com.hu.common.ErrorCode;
import com.hu.common.user.UserInfo;
import com.hu.constant.RedisConstant;
import com.hu.dao.UserDao;
import com.hu.exception.BusinessException;
import com.hu.exception.ThrowUtils;
import com.hu.pojo.dto.UserLoginRequest;
import com.hu.pojo.dto.UserQueryRequest;
import com.hu.pojo.dto.UserRegisterRequest;
import com.hu.pojo.dto.UserUpdateRequest;
import com.hu.pojo.entity.User;
import com.hu.utils.DeviceUtils;
import com.hu.service.UserService;
import com.hu.utils.BloomFilterUtil;
import com.hu.utils.RandomNameUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBitSet;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import static com.hu.constant.CommonConstant.SALT;
import static com.hu.constant.UserConstant.FALSE_PROBABILITY;
import static com.hu.constant.UserConstant.USER_DISTINCT_NAME;
import static com.hu.constant.UserConstant.USER_LOGIN_STATE;


/**
 * @author 20272
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-09-24 22:41:22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final RedissonClient redissonClient;

    private final BloomFilterUtil bloomFilterUtil;

    private final UserDao userDao;

    private String pattern = "^[A-Za-z0-9]+$";


    @PostConstruct
    public void init() {
        // 启动项目时初始化bloomFilter
        List<User> userList = userDao.list();
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        RBloomFilter bloomFilter = bloomFilterUtil.create(USER_DISTINCT_NAME, userList.size(), FALSE_PROBABILITY);
        for (User user : userList) {
            bloomFilter.add(user.getUserName());
        }
    }


    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        // 校验账号的非法性 只允许英文、数字
        boolean matches = userAccount.matches(pattern);
        if (!matches) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号非法");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // TODO
        synchronized (userAccount.intern()) {
            // 账户不能重复 TODO 是否也可以使用布隆？
            long count = userDao.selectCount(userAccount);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            // 默认是男
            user.setSex(0);
            // 随机生成昵称
            user.setUserName(RandomNameUtils.getRandomJianHan(5));
            // TODO 头像(默认 xiaoxiong.png)
            boolean saveResult = userDao.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public UserInfo userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        User user = userDao.getUserByAccountAndPassword(userAccount, encryptPassword);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        StpUtil.login(user.getId(), DeviceUtils.getRequestDevice(request));
        UserInfo userInfo = UserBuilder.buildUserInfo(user);
        StpUtil.getSession().set(USER_LOGIN_STATE, userInfo);
        return userInfo;
    }


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从会话中获取用户对象
        User user = (User) StpUtil.getSession().get(USER_LOGIN_STATE);
        // 如果用户对象不存在，则抛出异常
        if (user == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        // 返回用户对象
        return user;
    }

    /**
     * 用户登出
     */
    @Override
    public boolean userLogout() {
        StpUtil.checkLogin();
        // 移除登录态
        StpUtil.logout();
        return true;
    }


    /**
     * 添加用户签到记录
     *
     * @param userId 用户 id
     * @return 当前用户是否已签到成功
     */
    @Override
    public boolean addUserSignIn(long userId) {
        LocalDate date = LocalDate.now();
        String key = RedisConstant.getUserSignInRedisKey(date.getYear(), userId);
        // 获取 Redis 的 BitMap
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        // 获取当前日期是一年中的第几天，作为偏移量（从 1 开始计数）
        int offset = date.getDayOfYear();
        // 查询当天有没有签到
        if (!signInBitSet.get(offset)) {
            // 如果当前未签到，则设置
            signInBitSet.set(offset, true);
        }
        // 当天已签到
        return true;
    }

    /**
     * 获取用户某个年份的签到记录
     *
     * @param userId 用户 id
     * @param year   年份（为空表示当前年份）
     * @return 签到记录映射
     */
    @Override
    public List<Integer> getUserSignInRecord(long userId, Integer year) {
        if (year == null) {
            LocalDate date = LocalDate.now();
            year = date.getYear();
        }
        String key = RedisConstant.getUserSignInRedisKey(year, userId);
        // 获取 Redis 的 BitMap
        RBitSet signInBitSet = redissonClient.getBitSet(key);
        // 加载 BitSet 到内存中，避免后续读取时发送多次请求
        BitSet bitSet = signInBitSet.asBitSet();
        // 统计签到的日期
        List<Integer> dayList = new ArrayList<>();
        // 从索引 0 开始查找下一个被设置为 1 的位
        int index = bitSet.nextSetBit(0);
        while (index >= 0) {
            dayList.add(index);
            // 继续查找下一个被设置为 1 的位
            index = bitSet.nextSetBit(index + 1);
        }
        return dayList;
    }

    @Override
    public Page<User> pages(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        return userDao.pages(userQueryRequest);
    }

    @Override
    public boolean removeById(Long id) {
        return userDao.removeById(id);
    }

    @Override
    public boolean update(UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        return userDao.updateById(user);
    }

    @Override
    public User getById(long id) {
        return userDao.getById(id);
    }

    @Override
    public boolean updateById(User user) {
        return userDao.updateById(user);
    }

}




